package cn.chenhuanming.shh.authentication.server.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by chenhuanming on 2017-07-14.
 *
 * @author chenhuanming
 */
public class FailureHandler implements AuthenticationFailureHandler {

    private final String USER_NOT_FOUND = "帐号不存在!";
    private final String WRONG_PASSWORD = "密码错误!";
    private final String USER_LOCKED = "帐号已关闭!";
    private final String UNKNOW_ERROR = "未知错误!";

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        try (OutputStream os  = response.getOutputStream()){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());

            if(exception instanceof UsernameNotFoundException)
                mapper.writeValue(os,USER_NOT_FOUND);
            else if (exception instanceof BadCredentialsException)
                mapper.writeValue(os,WRONG_PASSWORD);
            else if(exception instanceof DisabledException)
                mapper.writeValue(os,USER_LOCKED);
            else
                mapper.writeValue(os,UNKNOW_ERROR);
        }
    }
}
